package logic

import (
	"context"
	"fmt"

	"gb28181/gb28181"
	"gb28181/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealPlayLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealPlayLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealPlayLogic {
	return &RealPlayLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 视频流控制接口
func (l *RealPlayLogic) RealPlay(in *gb28181.RealPlayRequest) (*gb28181.RealPlayResponse, error) {
	// 检查设备是否存在
	device, exists := l.svcCtx.ClientMgr.GetDevice(in.DeviceId)
	if !exists {
		return &gb28181.RealPlayResponse{
			Success: false,
			Message: "设备不存在",
		}, nil
	}

	// 检查设备是否在线
	if !device.IsOnline() {
		return &gb28181.RealPlayResponse{
			Success: false,
			Message: "设备不在线",
		}, nil
	}

	// 构建RTSP流URL
	rtspUrl := l.buildRTSPUrl(in.DeviceId, in.ChannelId)

	return &gb28181.RealPlayResponse{
		Success: true,
		Message: "实时播放启动成功",
		StreamUrl: rtspUrl,
	}, nil
}

// 构建RTSP流URL
func (l *RealPlayLogic) buildRTSPUrl(deviceId, channelId string) string {
	// 根据配置构建RTSP流URL
	config := l.svcCtx.Config.GB28181Config
	return fmt.Sprintf("rtsp://%s:%d/%s/%s", config.SIPServerHost, 554, deviceId, channelId)
}
